<template>
	<div>
		<van-field class="wz" label="账号" placeholder="请输入账号" v-model="loginForm.name" />
		<van-field class="wz" label="密码" placeholder="请输入密码" type="password" v-model="loginForm.password">
		</van-field>
		<div style="margin: 16px;">
		  <van-button round block style="background-color: #06cb62; color: #FFFFFF" @click="onClickLogin">登录</van-button>
		</div>
		<div style="margin: 16px;">
		  <van-button round block style="background-color: #f0db50; color: #FFFFFF" @click="onRegister">若还没有账号？点击注册</van-button>
		</div>
	</div>
</template>

<script>
	import {
		loginAPI
	} from "@/api/user.js";
	import {
		getUserLocal,
		setUserLocal,
		setTokenLocal
	} from "@/utils/auth.js";
	export default {
		name: "login",
		data() {
			return {
				loginForm: {
					name: "dingding", //设置默认值，仅是方便调试
					password: "123456",
				},
			};
		},
		mounted() {
			//初始赋值 ，从本地存储中获取用户名
			this.loginForm.name = getUserLocal().name;
		},
		methods: {
			//处理用户登录
			onClickLogin() {
				if (this.loginForm.name === "" || this.loginForm.password === "") {
					this.$toast("账号或密码不能为空");
					return;
				}
				let params = this.loginForm;
				loginAPI(params).then(result => {
					this.$toast({
						message: "登录成功！",
						duration: 1000
					});
					//本地保存用户信息（id,name）保存Token
					setTokenLocal(result.data.token);
					setUserLocal(result.data.user);
					//登录成功后跳转到需要重定向的路径，默认是我的页面（user）
					let toPath = this.$route.params.redirect || "user";
					setTimeout(() => {
						this.$router.replace({
							path: toPath
						});
					}, 1000);
				});
			},
			//处理用户注册
			onRegister() {
				//路由跳转到用户注册页面
				this.$router.push({
					name: "register"
				})
			}
		}
	}
</script>

<style lang="less" scoped>
	
</style>
